<?php

abstract class Skjb_Db_Table_Abstract extends Zend_Db_Table_Abstract
{
    protected $_rowsetClass = 'Skjb_Db_Table_Rowset';
    protected $_idRegistry = false;
    
    public function fetchRowById($id)
    {
        if ($this->_idRegistry) {
            $result = Skjb_Db_Table_Row_Registry::getItem($this->_name, $id);
            if ($result !== false) {
                return $result;
            }
        }
        
        $result = $this->fetchRow(array(
            (is_array($this->_primary) ? $this->_primary[1] : $this->_primary) . ' = ?' => $id,
        ));
        
        if ($this->_idRegistry) {
            Skjb_Db_Table_Row_Registry::setItem($this->_name, $id, $result);
        }
        
        return $result;
    }
    
    public function getName()
    {
        return $this->_name;
    }
    
    public function truncate()
    {
        return $this->getAdapter()->query('TRUNCATE `' . $this->_name . '`');
    }
    
    public function fetchOne($field, $where = array(), $sort = null)
    {
        $select = $this->select();
        $select->from($this->_name, array($field));
        foreach ($where as $key => $value) {
            $select->where($key, $value);
        }
        if ($sort !== null) {
            $select->order($sort);
        }
        return $this->getAdapter()->fetchOne($select);
    }
    
    public function fetchCol($field, $where = array(), $sort = null, $count = null, $offset = null)
    {
        $select = $this->select();
        $select->from($this->_name, array($field));
        if (is_array($where)) {
            foreach ($where as $key => $value) {
                $select->where($key, $value);
            }
        }
        if ($sort !== null) {
            $select->order($sort);
        }
        $select->limit($count, $offset);
        return $this->getAdapter()->fetchCol($select);
    }
    
    public function __get($name)
    {
        if (substr($name, -5) == 'Table') {
            return Skjb_Db_Table_Registry::getTable($name);
        }
        
        return parent::__get($name);
    }
}